package com.lancoo.answer.view.fragment.option

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.animation.TranslateAnimation
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.lancoo.answer.R
import com.lancoo.answer.component.OptionComponent
import com.lancoo.answer.databinding.EvViewClozeBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.Item
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.combinationView.FillContextAnswerResultView
import com.lancoo.answer.widget.combinationView.ReadingMatchQueseBodyView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @Description 作答模式匹配题的选择部分
 * @Author dadong
 * @Date 05-31-2022 周二 11:31
 */
class MultiChildFragment : BaseVMFragment<EvViewClozeBinding>() {

    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0
    private var chooseCallback: SingleOptionFragment.ChooseCallback? = null
    private var currentPosition: Int = 0
    private var pageChangeCallback: PageChangeCallback? = null
    private var isScrolled = false

    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val multiChildFragment = MultiChildFragment()
            multiChildFragment.arguments = mBundle
            return multiChildFragment
        }
    }

    override fun initView(view: View) {
        EventBus.getDefault().register(this)
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        if (ques.GenreID == "0") {
            mBinding.childStatisticsView.visibility = View.GONE
        } else {
            mBinding.childStatisticsView.setQues(ques)
        }
        initVp()
    }

    private fun initVp() {
        mBinding.vpChildAsk.adapter =
            object : FragmentStateAdapter(childFragmentManager, lifecycle) {
                override fun getItemCount(): Int {
                    return if (ques.SpecialFeatureCodes == "46") //双组匹配
                        ques.ChildList!!.size
                    else {
                        1
                    }
                }

                override fun createFragment(position: Int): Fragment {
                    val singleOptionFragment =
                        SingleOptionFragment.loadFragment(
                            typeIndex,
                            quesIndex,
                            defaultLoadIndex
                        ) as SingleOptionFragment

                    if (chooseCallback != null) {
                        singleOptionFragment
                            .setChooseCallback(chooseCallback!!)
                    }
                    singleOptionFragment.setDeepable(false)
                    singleOptionFragment.setMultiable(true)
                    singleOptionFragment.setChildIndex(position)
                    singleOptionFragment.setTvChildVisibility(View.GONE)

                    return singleOptionFragment
                }
            }

        mBinding.vpChildAsk.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mBinding.childStatisticsView.updateChildIndex(position)
                currentPosition = position
                if (isScrolled) {
                    EventBus.getDefault().post(position)
                    pageChangeCallback?.callback(position)
                }
                FragmentCommunicationUtils.switchTestQuesionToEvent(
                    typeIndex,
                    quesIndex,
                    currentPosition,
                    false,
                    1
                )
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                if (positionOffset > 0)
                    isScrolled = true
            }
        })

        if (defaultLoadIndex != -1 && defaultLoadIndex < ques.ChildList!!.size) {
            mBinding.vpChildAsk.postDelayed(Runnable {
                mBinding.vpChildAsk.currentItem = defaultLoadIndex
            }, 200)
        }
    }

    fun setChooseCallback(chooseCallback: SingleOptionFragment.ChooseCallback) {
        this.chooseCallback = chooseCallback
    }

    //换页
    fun nextChildAsk(position: Int? = -1) {
        isScrolled = true
        // 切换到下一页
        if (position == null || position == -1) {
            getCurrentPosition()
            mBinding.vpChildAsk.setCurrentItem(currentPosition, true)
        } else {
            mBinding.vpChildAsk.setCurrentItem(position, true)
        }

    }

    private fun getCurrentPosition() {
        if (ques.SpecialFeatureCodes == "47|101") {
            FragmentCommunicationUtils.autoNextQuesFragment(this, true)
            return
        }
        currentPosition += 1
        if (currentPosition >= ques.ChildList!!.size) {
            currentPosition = ques.ChildList!!.size - 1
            FragmentCommunicationUtils.autoNextQuesFragment(this, true)
            return
        }
    }

    fun showResultView(item: Item) {
        if (ConstantBean.taskControlBean!!.trainSence == 1 || ConstantBean.taskControlBean!!.trainSence == 2
            || ConstantBean.taskControlBean!!.trainSence == 3
        ) {
            return
        }
        val fillContextAnswerResultView: FillContextAnswerResultView =
            mBinding.resultView.root.findViewById(R.id.fill_context_answer)
        val typeNo = ques.TypeNo
        fillContextAnswerResultView.setFillResult(item)
        mBinding.resultView.root.findViewById<View>(R.id.ll_close)
            .setOnClickListener { v: View? -> mBinding.resultView.root.visibility = View.GONE }
        if (ConstantBean.taskControlBean!!.expired) {
            fillContextAnswerResultView.showAnalysisAndAnswer()
        }
        if (TextUtils.equals("m", typeNo)) { //匹配题只显示答案解析
            fillContextAnswerResultView.onlyShowAnalysis()
        }
        val ctrlAnimation = TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_SELF, 0f, TranslateAnimation.RELATIVE_TO_SELF, 0f,
            TranslateAnimation.RELATIVE_TO_SELF, 1f, TranslateAnimation.RELATIVE_TO_SELF, 0f
        )
        ctrlAnimation.duration = 400
        mBinding.resultView.root.visibility = View.VISIBLE
        mBinding.resultView.root.startAnimation(ctrlAnimation)
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_view_cloze
    }

    fun setPageChangeCallback(pageChangeCallback: PageChangeCallback) {
        this.pageChangeCallback = pageChangeCallback
    }

    interface PageChangeCallback {
        fun callback(position: Int)
    }

    fun setCurrentItem(itemIndex: Int) {
        mBinding.vpChildAsk.currentItem = itemIndex
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEventMainThread(bean: Item) {
        showResultView(bean)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    fun adjustFontSize() {
        if ( mBinding.vpChildAsk.getChildAt(currentPosition)!=null)
        mBinding.vpChildAsk.getChildAt(currentPosition).findViewById<OptionComponent>(R.id.option_component).adjustFontSize()
    }

    fun markQuestion() {
        if ( mBinding.vpChildAsk.getChildAt(currentPosition)!=null)
        mBinding.vpChildAsk.getChildAt(currentPosition)
            .findViewById<OptionComponent>(R.id.option_component).markQuestion()
    }
}